package com.hiwhitley.himei.network;

import android.util.Log;

import com.hiwhitley.himei.BuildConfig;
import com.hiwhitley.himei.app.App;
import com.hiwhitley.himei.network.service.GameService;
import com.hiwhitley.himei.network.service.GankService;
import com.hiwhitley.himei.network.service.OpenEyesService;
import com.hiwhitley.himei.utils.NetworkUtil;
import com.ihsanbal.logging.Level;
import com.ihsanbal.logging.LoggingInterceptor;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by hiwhitley on 2016/9/22.
 */

public class RetrofitFactory {

    public static final String GANK_URL = "http://gank.io/api/";
    public static final String OPEN_EYE_URL = "http://baobab.wandoujia.com/";
    public static final String GAME_URL = "https://ypw.netease.com/";

    private static Retrofit retrofit;
    private volatile static GankService sGankService;
    private volatile static OpenEyesService sOpenEyesService;
    private volatile static GameService sGameService;

    // 连接超时时间，默认20秒
    private static final int CONNECT_TIMEOUT = 20;

    private RetrofitFactory() {

    }

    private static <T> T configRetrofit(Class<T> clazz, String URL, boolean needToken) {
        retrofit = new Retrofit.Builder()
                .baseUrl(URL)
                .client(configClient(needToken))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit.create(clazz);
    }

    private static OkHttpClient configClient(boolean needToken) {

        File httpCacheDirectory = new File(App.getContext().getCacheDir(), "HttpCache");

        OkHttpClient client;
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .addNetworkInterceptor(new CacheInterceptor())
                .addInterceptor(new CacheInterceptor())
                .cache(new Cache(httpCacheDirectory, 20 * 1024 * 1024));

        if (BuildConfig.isDebug) {
            builder.addInterceptor(new LoggingInterceptor.Builder()
                    .loggable(BuildConfig.DEBUG)
                    .setLevel(Level.BASIC)
                    .log(Log.INFO)
                    .request("Request")
                    .response("Response")
                    .addHeader("version", BuildConfig.VERSION_NAME)
                    .build());

        }

        if (needToken) {
            client = builder.addInterceptor(new TokenInterceptor())
                    .build();
        } else {
            client = builder.build();
        }
        return client;
    }

    public static GankService getGankService() {
        if (sGankService == null) {
            synchronized (RetrofitFactory.class) {
                if (sGankService == null) {
                    sGankService = configRetrofit(GankService.class, GANK_URL, false);
                }
            }
        }
        return sGankService;
    }


    public static GameService getGameService() {
        if (sGameService == null) {
            synchronized (RetrofitFactory.class) {
                if (sGameService == null) {
                    sGameService = configRetrofit(GameService.class, GAME_URL, true);
                }
            }
        }
        return sGameService;
    }

    public static OpenEyesService getOpenEyesService() {
        if (sOpenEyesService == null) {
            synchronized (RetrofitFactory.class) {
                if (sOpenEyesService == null) {
                    sOpenEyesService = configRetrofit(OpenEyesService.class, OPEN_EYE_URL, false);
                }
            }
        }
        return sOpenEyesService;
    }

}
